package com.caszx.chargingpile.fragment.battery;


import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
import com.app.base.fragment.BaseFragment;
import com.caszx.chargingpile.R;
import com.caszx.chargingpile.activity.BatteryScannedActivity;
import com.caszx.chargingpile.activity.BluetoothActivity;
import com.caszx.chargingpile.activity.ChargeListActivity;
import com.caszx.chargingpile.eventbus.EventBusAction;
import com.caszx.chargingpile.utils.DialogHelp;
import com.jakewharton.rxbinding.view.RxView;
import com.jakewharton.rxbinding.widget.RxCompoundButton;

import java.util.concurrent.TimeUnit;

import cn.bingoogolapple.qrcode.core.QRCodeView;
import cn.bingoogolapple.qrcode.zxing.ZXingView;
import de.greenrobot.event.EventBus;
import rx.functions.Action1;

/**
 * 充电首页：二维码扫描
 */
public class QRCodeHomeFragment extends BaseFragment implements QRCodeView.ResultHandler {

    private static int CAMERA_REQUEST_CODE = 1;
    private static int FLASHLIGHT_REQUEST_CODE = 2;
    private ZXingView mQRCodeView;
    private CheckBox check_light;
    private CheckBox check_bluetooth;

    public static QRCodeHomeFragment newInstance() {
        QRCodeHomeFragment fragment = new QRCodeHomeFragment();
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            mQRCodeView.stopCamera();
            check_light.setChecked(false);
        } else {
            mQRCodeView.startSpotAndShowRect();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == CAMERA_REQUEST_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
                mQRCodeView.startSpotAndShowRect();
            } else {
                // Permission Denied
            }
        } else if (requestCode == FLASHLIGHT_REQUEST_CODE) {
            //打开闪光灯
            mQRCodeView.openFlashlight();
        }
    }

    public void onEvent(String action) {
        if (EventBusAction.ACTION_USER_PAY_SUCCESS.equals(action)) {
            //付款成功
            DialogHelp.showDialogOnlyMesg(getContext(), "支付成功", null);
        }
    }


    @Override
    protected View initView() {
        View view = getActivity().getLayoutInflater().inflate(
                R.layout.fragment_qrcode, null);
        findViewById(view);
        initToobar(view);
        //6.0权限检查
        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            //申请CAMERA权限
            requestPermissions(new String[]{Manifest.permission.CAMERA}, CAMERA_REQUEST_CODE);
        }
        return view;
    }

    private void initToobar(View view) {
        Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
        toolbar.setNavigationIcon(null);
        toolbar.inflateMenu(R.menu.menu_station_hamburger);
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                //充电列表
                Intent intent = new Intent(getContext(), ChargeListActivity.class);
                startActivity(intent);
                return true;
            }
        });
        TextView centerText = (TextView) view.findViewById(R.id.center_title);
        centerText.setText("充电");

    }

    private void findViewById(View view) {
        mQRCodeView = (ZXingView) view.findViewById(R.id.zxingview);
        check_light = (CheckBox) view.findViewById(R.id.check_light);
        check_bluetooth = (CheckBox) view.findViewById(R.id.check_bluetooth);

        RxCompoundButton.checkedChanges(check_light).throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean isChecked) {
                        if (isChecked) {
                            mQRCodeView.openFlashlight();
//                            //6.0权限检查
//                            if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.FLASHLIGHT) != PackageManager.PERMISSION_GRANTED) {
//                                //申请CAMERA权限
//                                requestPermissions(new String[]{Manifest.permission.FLASHLIGHT}, FLASHLIGHT_REQUEST_CODE);
//                            }
                        } else {
                            mQRCodeView.closeFlashlight();
                        }
                    }
                });

        RxView.clicks(check_bluetooth).throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        Intent intent = new Intent(getActivity(), BluetoothActivity.class);
                        startActivity(intent);
                    }
                });
        mQRCodeView.setResultHandler(this);
        mQRCodeView.startSpotAndShowRect();
    }


    private void vibrate() {
        Vibrator vibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
        vibrator.vibrate(200);
    }

    @Override
    public void handleResult(String result) {
        Intent intent = new Intent(getActivity(), BatteryScannedActivity.class);
        intent.putExtra("CODE", result);
        intent.putExtra("TITLE", BatteryScannedActivity.TITLE_SCANN);
        getActivity().startActivity(intent);
        vibrate();
//        mQRCodeView.closeFlashlight();
//        mQRCodeView.stopCamera();
        mQRCodeView.stopSpotAndHiddenRect();
    }

    @Override
    public void handleCameraError() {

    }

    @Override
    public void onResume() {
        super.onResume();
        mQRCodeView.startCamera();
        mQRCodeView.startSpotAndShowRect();
    }

    @Override
    public void onPause() {
        super.onPause();
        mQRCodeView.stopCamera();
        mQRCodeView.stopSpotAndHiddenRect();
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        mQRCodeView.closeFlashlight();
        mQRCodeView.stopCamera();
        mQRCodeView.stopSpotAndHiddenRect();
        super.onDestroy();
    }
}
